import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {SubscriptionService} from './subscription.service';
import {NzCascaderOption} from 'ng-zorro-antd/cascader';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-subscription',
  templateUrl: './subscription.component.html',
  styleUrls: ['./subscription.component.less']
})
export class SubscriptionComponent implements OnInit {
  validateForm: FormGroup;
  fieldOptions: NzCascaderOption[] = [];
  areasList = [];
  areasCondition: string[] = [];
  isVisible = false;
  deleteEmail: string;
  objectKeys = Object.keys;

  get field(): any {
    return this.validateForm.get('field');
  }

  constructor(private fb: FormBuilder,
              private subService: SubscriptionService,
              private message: NzMessageService) {
    this.validateForm = this.fb.group({
      //email: ['', [Validators.email, Validators.required]],
      email: ['', [Validators.required]],                           // 1219, 为了演示速度, 不验证email格式。
      // field: ['', [Validators.required]],
      field: this.fb.array([this.fb.control('')]),
      areas: ['', [Validators.required]]
    });
  }

  ngOnInit(): void {
    this.getFieldList();
    this.getAreas();
  }

  submitForm(): void {
    const fieldOptions = [];
    const field = this.validateForm.controls.field.value;
    for (const fieldItem of field) {
      const length = fieldItem[fieldItem.length - 1];
      // 判断是否是数字，是的话push
      if (typeof length === 'number' && !isNaN(length)) {
        fieldOptions.push(length);
      }
    }
    const emailValue = this.validateForm.controls.email.value;
    if (this.areasCondition.length) {
      this.subService.submitForm({
        email: emailValue,
        wordFreamIds: fieldOptions,
        region: this.areasCondition
      }).subscribe(res => {
        this.message.info(res.msg);
      });
    } else {
      this.message.create('error', '请选择发布地域');

    }
  }

  getFieldList() {
    this.subService.getFieldList().subscribe(res => {
      this.fieldOptions = res.result;
    });
  }

  getAreas() {
    this.subService.getAreas().subscribe(res => {
      this.areasList = res.result;
      // this.validateForm.controls.areas.setValue(res.result);

    });
  }

  addField() {
    this.pushRoleLine();
  }

  selectedAdd(value: string[]) {
    this.validateForm.controls.areas.setValue(value);
    this.areasCondition = value;

  }

  saveChecked() {
    this.areasCondition = [];
    for (const area of this.areasList) {
      if (area.checked) {
        this.areasCondition.push(area.value);
      }
    }

  }

  handleCancel() {
    this.isVisible = false;
  }

  handleOk() {
    this.subService.cancelSubmit(this.deleteEmail).subscribe(res => {
      this.message.info(res.msg);
    });
    this.isVisible = false;
  }

  pushRoleLine() {
    this.field.push(
      this.fb.control('')
    );
  }

}
